package com.zjshell.pricing.site.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjshell.pricing.common.entity.FebsConstant;
import com.zjshell.pricing.common.entity.QueryRequest;
import com.zjshell.pricing.common.utils.SortUtil;
import com.zjshell.pricing.site.entity.ShellSite;
import com.zjshell.pricing.site.mapper.ShellSiteMapper;
import com.zjshell.pricing.site.service.IShellSiteService;
import com.zjshell.pricing.system.entity.User;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ShellSiteServiceImpl extends ServiceImpl<ShellSiteMapper, ShellSite> implements IShellSiteService{

	@Autowired
	private ShellSiteMapper shellSiteMapper;

	@Override
	public ShellSite findById(Long siteid) {
		return shellSiteMapper.findById(siteid);
	}

	@Override
	public IPage<ShellSite> findShellSiteDetail(ShellSite shellSite, QueryRequest request) {
		Page<ShellSite> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "site_code", FebsConstant.ORDER_ASC, false);
        return this.baseMapper.findShellSiteDetailPage(page, shellSite);
	}


	@Override
	public void createShellSite(ShellSite shellSite) {
		this.baseMapper.insert(shellSite);
	}

	@Override
	public void deleteShellSites(String[] siteids) {
		delete(Arrays.asList(siteids));
	}

	@Override
	public void updateShellSite(ShellSite shellSite) {
		this.baseMapper.updateById(shellSite);
		
	}
	
	private void delete(List<String> siteids) {
        removeByIds(siteids);
        LambdaQueryWrapper<ShellSite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ShellSite::getSiteid, siteids);
        List<ShellSite> shellSites = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(shellSites)) {
            List<String> dseptIdList = new ArrayList<>();
            shellSites.forEach(d -> dseptIdList.add(String.valueOf(d.getSiteid())));
            this.delete(dseptIdList);
        }
    }


	@Override
	public List<ShellSite> findShellSiteDetail(ShellSite shellSite) {
		return shellSiteMapper.findShellSiteDetail(shellSite);
	}

	@Override
	public Long getshellsiteId() {
		return shellSiteMapper.getshellsiteId();
	}

}
